﻿import { routerWhiteList } from '@/router/utils/public'
import { storeToRefs } from 'pinia'
import { usePublicStore } from '@/store/public/publicStore'
import { useSystemConfigStore } from '@/store/storage/systemConfigStore'

const useScrollListener = (route, callback?: (a: number) => void) => {
  const systemConfigStore = useSystemConfigStore()
  const { systemConfig } = storeToRefs(systemConfigStore)
  const publicStore = usePublicStore()
  const { scrollTopHeight } = storeToRefs(publicStore)
  // 获取当前页面的缓存状态是否被开启
  const isKeepAlive = route.meta.keepAlive
  // 非缓存页面开启监听
  const mountedScrollListener = () => {
    // 未开启页面状态缓存的情况下，监听事件在此声明周期内开启
    if ((systemConfig.value.isKeepAlive && !isKeepAlive) || !systemConfig.value.isKeepAlive) {
      // 开启滚动监听事件
      window.addEventListener('scroll', handleScroll, true)
    }
  }
  // 非缓存页面移除监听
  const beforeUnmountScrollListener = () => {
    // 未开启页面状态缓存的情况下，监听事件在此声明周期内移除
    if ((systemConfig.value.isKeepAlive && !isKeepAlive) || !systemConfig.value.isKeepAlive) {
      // 移除滚动监听事件
      window.removeEventListener('scroll', handleScroll, true)
    }
  }
  // 缓存页面开启监听
  const activatedScrollListener = () => {
    // 未开启页面状态缓存的情况下，监听事件在此声明周期内移除
    if (systemConfig.value.isKeepAlive && isKeepAlive) {
      // 开启滚动监听事件
      window.addEventListener('scroll', handleScroll, true)
    }
  }
  // 缓存页面移除监听
  const deactivatedScrollListener = () => {
    // 未开启页面状态缓存的情况下，监听事件在此声明周期内移除
    if (systemConfig.value.isKeepAlive && isKeepAlive) {
      // 移除滚动监听事件
      window.removeEventListener('scroll', handleScroll, true)
    }
  }
  // 在组件挂载到页面后执行
  onMounted(mountedScrollListener)
  // 页面未启用keep-alive时，则需要在此生命周期函数内（组件被卸载之前执行）移除监听
  onBeforeUnmount(beforeUnmountScrollListener)
  // keep-alive启用时，页面被激活时使用
  onActivated(activatedScrollListener)
  // 页面启用keep-alive时，则需要在此生命周期函数内（组件切换，老组件消失的时候执行）移除监听事件
  onDeactivated(deactivatedScrollListener)
  // 滚动监听执行事件
  const handleScroll = () => {
    const scrollTop = document.querySelector('.vk-scroll-wrap').scrollTop
    if (routerWhiteList.selfScroll.includes(route.name) && (!systemConfig.value.isFixedHeader || !systemConfig.value.isFixedSidebar)) {
      scrollTopHeight.value = scrollTop
    }
    if (callback) {
      callback(scrollTop)
    }
  }
  return {
    scrollTopHeight
  }
}
export default useScrollListener
